<template>
  <common-list-group class="report-component-wrap">
    <div slot="group" class="group-list-component-wrap">
      <div class="group-header-wrap">
        <div class="group-header-title">自助看板分类</div>
      </div>
      <common-tree
        :isRequest="isRequest"
        :treeLoading="treeLoading"
        ref="treeRef"
        :is-slot="true"
        :tree-data="groupTreeData"
        :treeProp="{ isLeaf: 'leaf' }"
        search-placeholder="查询分类"
        :current-node-key="currentNodeKey"
        :hiddenIndexIcon="3"
        setNodeByKey="leaf"
        isShowIconForNoChild
        @handleNodeClick="handleNodeClick"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14" />

          <el-popover
            v-if="scope.data.isDefault === 0"
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <commonIcon
              slot="reference"
              iconName="icon-more"
              iconType="icon"
              :iconSize="16"
            ></commonIcon>
            <common-menu>
              <common-menu-item
                v-if="scope.node.level < 3"
                v-has-permi="['system:subject:add']"
                @click="treeAdd(scope.data)"
                >新增子分类
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                v-has-permi="['system:subject:edit']"
                @click="treeEdit(scope.data)"
                >编辑
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                v-has-permi="['system:subject:remove']"
                @click="handleDeleteTree(scope.data.id)"
                >删除
              </common-menu-item>
            </common-menu>
          </el-popover>
        </div>
      </common-tree>
    </div>

    <!--新增分类弹窗-->
    <common-edit-dialog
      :title="`${isTypeEdit ? '编辑' : '新增'}分类`"
      :visible="isTypeDialog"
      :button-loading="dialogLoading"
      @cancel="typeDialogCancel"
      @submit="addTypeForm"
      width="25%"
    >
      <el-form
        ref="typeForm"
        :model="typeForm"
        :rules="typeRule"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="分类名称" prop="name">
          <common-input :maxlength="16" v-model="typeForm.name"></common-input>
        </el-form-item>
        <!-- <common-add-dept
          ref="commonAddDept"
          :deptListParams="departmentList"
          @getCheckedDeptId="getCheckedDeptId"
          :deptId="typeForm.deptId"
        ></common-add-dept> -->
      </el-form>
    </common-edit-dialog>

    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        :inline="true"
        label-width="63px"
      >
        <el-form-item label="看板名称" prop="name">
          <common-input v-model="query.name" clearable @enter="handleQuery" />
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 按钮部门start -->
    <el-row :gutter="10" class="mb8" slot="tools" v-if="!predefined">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="hasType"
          @click="add(null)"
          plain
          v-has-permi="['system:kanban:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          :disabled="!showBatch"
          @click="handleDelete()"
          v-has-permi="['system:kanban:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <!--列表 start-->
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="看板名称"
        align="left"
        prop="name"
        show-overflow-tooltip
        fixed="left"
      ></el-table-column>
      <el-table-column label="状态" align="left" prop="time">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status === 0">启用</el-tag>
          <el-tag type="danger" v-else-if="row.status === 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="preview(scope.row)"> 预览</el-button>
          <el-button
            type="text"
            v-if="!predefined"
            v-has-permi="['system:kanban:classIfication']"
            @click="branch(scope.row)"
          >
            分类
          </el-button>
          <el-button
            type="text"
            v-if="!predefined"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
            v-has-permi="['system:kanban:stop']"
          >
            {{ scope.row.status === 0 ? "停用" : "启用" }}
          </el-button>
          <el-button
            type="text"
            v-if="($route.query.super_dev === 'true' && isAdmin) || !predefined"
            v-has-permi="['system:subject:edit']"
            @click="edit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            v-if="!predefined"
            @click="handleDelete(scope.row)"
            v-has-permi="['system:subject:remove']"
          >
            删除</el-button
          >
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <!--看板更换分类弹窗-->
    <common-edit-dialog
      title="切换分类"
      width="25%"
      :visible="isShowTypeListDialog"
      :button-loading="typeLoading"
      @cancel="updateTypeDialogCancel"
      @submit="updateTypeSubmit"
    >
      <el-form
        ref="updateTypeForm"
        :model="updateTypeForm"
        :rules="updateTypeRule"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="typeId">
          <el-cascader
            style="width: 100%"
            v-model="updateTypeForm.typeId"
            :show-all-levels="false"
            :options="typeList"
            :props="props"
            clearable
          >
            <template slot-scope="{ node, data }">
              <common-marquee-text :content="data.name"></common-marquee-text>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
    </common-edit-dialog>

    <!--新增看板-->
    <template v-if="isShowAdd">
      <add-view-board
        ref="addViewBoard"
        :departmentList="departmentList"
        :typeId="typeId"
        :typeName="typeName"
        @close="closeAdd"
        @refresh="getList"
      ></add-view-board>
    </template>

    <!--看板预览-->
    <template v-if="isShowPreview">
      <preview-view-board
        ref="previewVB"
        @close="isShowPreview = false"
      ></preview-view-board>
    </template>
  </common-list-group>
</template>

<script>
import {
  getTree,
  addType,
  editType,
  removeType,
  deleteTypeForCheck,
  getList,
  updateStatus,
  removeViewBoard,
  editViewBoard,
  classIfication,
  deleteForCheck,
} from "@/api/screenConfig/viewboard";
import commonIcon from "@/components/CommonIcon";

import BaseList from "@/mixins/BaseList";
import AddViewBoard from "./components/add";
import PreviewViewBoard from "./components/preview";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";

export default {
  name: "index",
  mixins: [BaseList],
  components: {
    AddViewBoard,
    PreviewViewBoard,
    commonIcon,
  },
  data() {
    return {
      isRequest: false,
      treeLoading: false,
      multiple: false,
      predefined: false,
      isShowAdd: false, //新增看板
      isShowPreview: false, //预览看板
      isTypeDialog: false, //分类弹窗
      isTypeEdit: false,
      loading: false, //列表loading
      dialogLoading: false,
      list: [], //看板列表数据集
      typeName: "",
      typeForm: {
        id: null,
        name: "",
        parentId: null,
        parentIds: "",
        isDefault: 0,
        deptId: null,
      },
      typeRule: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        // deptId: [{ required: true, message: "请选择组织", trigger: "blur" }],
      },
      query: {
        id: "0",
        name: "",
        parentId: "",
        isDefault: 0,
        pageNum: 1,
        pageSize: 10,
        deptIds: null,
      },
      total: 0,
      groupTreeData: [], //看板分类数据集
      typeId: "", //数据集分类id
      currentNodeKey: "0", //默认节点高亮
      isShowTypeListDialog: false, //列表更新分类
      typeLoading: false, //按钮loading
      typeList: [], //分类列表树形结构
      updateTypeForm: {
        typeId: null,
      },
      updateTypeRule: {
        typeId: [{ required: true, message: "请选择分类", trigger: "blur" }],
      },
      props: {
        checkStrictly: true,
        label: "name",
        value: "id",
      },
      currentParent: 1,
      singleDeptList: [],
      departmentList: [],
    };
  },
  computed: {
    ...mapGetters(["isAdmin"]),
    hasType: function () {
      return (this.typeId ?? "") === "";
    },
  },
  methods: {
    // getCheckedDeptId(val) {
    //   this.typeForm.deptId = val;
    // },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    // 查询
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
    },
    //树节点新增
    treeAdd(row) {
      this.typeForm.name = "";
      this.typeForm.remark = "";
      this.typeForm.id = "";
      this.typeForm.parentId = row.id ? row.id : 0;
      this.currentNodeKey = row.id;
      this.isTypeDialog = true;
      this.isTypeEdit = false;
    },
    //分类弹窗关闭
    typeDialogCancel() {
      this.isTypeDialog = false;
    },
    //树节点点击
    handleNodeClick(info) {
      // this.predefined = info.data.isDefault === 1
      // this.typeId = info.data.id
      // this.query.id = info.data.name === '自定义' || info.data.name === '预定义' ? '0' : info.data.id
      // this.query.isDefault = info.data.isDefault
      // this.typeName = info.data.name
      // this.query.pageNum = 1
      // this.query.pageSize = 10
      // this.getList()

      this.predefined = info.data.isDefault === 1;
      this.query.id =
        info.data.name === "自定义" || info.data.name === "预定义"
          ? "0"
          : info.data.id;
      this.typeId = info.data.id;
      this.query.isDefault = info.data.isDefault;
      this.typeName = info.data.name;
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.getList();
    },
    //分类弹窗提交按钮
    addTypeForm() {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (this.isTypeEdit) {
            editType(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("重命名成功");
                  this.isTypeDialog = false;
                  this.queryAllTree();
                } else {
                  this.$GlobalErrorConfirm("重命名失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          } else {
            addType(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.isTypeDialog = false;
                  this.queryAllTree();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          }
        }
      });
    },
    //树节点重命名
    treeEdit(row) {
      this.typeForm.name = row.name;
      this.typeForm.id = row.id;
      this.typeForm.parentId = row.parentId;
      this.typeForm.deptId = row.deptId;
      this.currentNodeKey = row.id;
      this.isTypeEdit = true;
      this.isTypeDialog = true;
    },
    // 树节点删除
    deleteTreeData(id) {
      this.currentNodeKey = id;
      this.$GlobalDeleteConfirm()
        .then(() => {
          removeType({ id: id }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              this.queryAllTree();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },

    /**
     * 左侧树形通用删除前校验方法
     */
    beforeDeleteTreeForCheck(id) {
      return new Promise((resolve, reject) => {
        deleteTypeForCheck({ id: id })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 预览
    preview(row) {
      this.isShowPreview = true;
      this.$nextTick(() => {
        this.$refs.previewVB.initData(row);
      });
    },
    ////新增看板按钮
    add() {
      this.isShowAdd = true;
    },
    /**
     * 启用/停用方法
     */
    changeStatus(row) {
      // row.isDisabledForShake = true
      return new Promise((resolve, reject) => {
        let status = row.status === 0 ? 1 : 0;
        updateStatus({ id: row.id, status: status })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              this.query.pageNum = 1;
              resolve(res);
              this.getList();
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg);
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    //分类取消弹窗
    closeAdd() {
      this.isShowAdd = false;
    },
    // 删除看板
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      let noDel = false;
      this.list.forEach((item) => {
        if (ids.includes(item.id) && item.status === 0) {
          noDel = true;
        }
      });
      if (noDel) {
        return this.$GlobalErrorConfirm("删除失败", " 启用状态下不允许删除");
      }

      this.$GlobalDeleteConfirm()
        .then(() => {
          removeViewBoard({ ids }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.query.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.query.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 编辑看板
    edit(row) {
      if (row.status === 0 && row.isDefault === 0) {
        return this.$GlobalErrorConfirm("编辑失败", " 启用状态下不允许编辑");
      }

      this.isShowAdd = true;
      this.$nextTick(() => {
        this.$refs.addViewBoard.initData(row);
      });
    },
    // 分类
    branch(row) {
      this.isShowTypeListDialog = true;
      //获取看板分类全路径
      const tmpData = []; // 路径数组
      const FindPos = (sourceTree, sourceId) => {
        if (!sourceTree.length) {
          return; // 空数组返回
        }
        sourceTree.forEach((item, index) => {
          if (item.id === sourceId) {
            tmpData.push(sourceId);
            if (item.id !== "0") {
              FindPos(this.typeList, item.parentId);
            } // 继续寻找上层元素数据
          } else {
            // 当前继续寻找别的子项
            if (item.children && item.children.length) {
              FindPos(item.children, sourceId);
            }
          }
        });
      };
      FindPos(this.typeList, row.parentId);
      this.updateTypeForm = {
        ...row,
        typeId: tmpData.reverse(),
      };
    },
    //更新分类
    updateTypeSubmit() {
      this.$refs.updateTypeForm.validate((valid) => {
        if (valid) {
          let params = {
            ...this.updateTypeForm,
            parentId:
              this.updateTypeForm.typeId[this.updateTypeForm.typeId.length - 1],
          };
          this.typeLoading = true;
          classIfication(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("编辑分类成功");
                this.updateTypeDialogCancel();
                this.getList();
              } else {
                this.$GlobalErrorConfirm("编辑分类失败", res.msg);
              }
            })
            .finally(() => (this.typeLoading = false));
        }
      });
    },
    //关闭更新分类弹窗
    updateTypeDialogCancel() {
      this.isShowTypeListDialog = false;
    },

    deleteChildren(treeData) {
      if (!treeData.length) {
        return;
      }
      treeData.forEach((item) => {
        if (item.children && item.children.length) {
          this.deleteChildren(item.children);
        } else {
          delete item.children;
        }
      });
    },

    //获取菜单分类数据
    queryAllTree() {
      this.treeLoading = true;
      getTree({})
        .then((res) => {
          if (res && res.code === 200) {
            // console.log("-->", res);
            this.groupTreeData = [
              {
                id: "0-0",
                name: "预定义", // 名称
                isDefault: 1, // 1 预定义 0 自定义
                leaf: false, // false 分类 true 数据集
                isRoot: true,
                children: res.data.filter((item) => item.isDefault === 1),
              },
              {
                id: "0",
                name: "自定义",
                isDefault: 0,
                leaf: false,
                isRoot: true,
                children: res.data.filter((item) => item.isDefault === 0),
              },
            ];
            this.typeList = [this.groupTreeData[1]];
            this.deleteChildren(this.typeList);
            this.typeName = "自定义";
            this.typeId = "0";
            this.getList();
          } else {
            this.groupTreeData = [];
            this.typeList = [];
            this.handleListTips(res);
          }
        })
        .finally(() => (this.treeLoading = false));
    },
    //获取列表数据
    getList() {
      this.loading = true;
      this.isRequest = true;
      getList(this.query)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
                deptName: this.getDeptName(c.deptId || ""),
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
          this.isRequest = false;
        });
    },
  },

  mounted() {
    this.queryAllTree();
  },
};
</script>

<style scoped lang="scss">
.report-component-wrap {
  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    &:hover {
      .iconfont {
        opacity: 1;
      }
    }

    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }

    .tree-label {
      margin-right: 4px;
    }

    .pre-icon {
      width: 12px;
      height: 12px;
      font-size: 12px;
    }
  }

  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }
}
</style>
